package com.example.test.advice.第二章_基本类型.建议22_用整数类型处理货币;

import java.math.BigDecimal;
import java.math.MathContext;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class MoneyClient {

    public static void main(String[] args) {
        test1();
        System.out.println("======test2");
        test2();
        System.out.println("======test3");
        test3();
        System.out.println(9.61f*100);
        //9.61   2*1  10.22  2*2  10.44  2*3 10.88 2* 4 11.76
        System.out.println(9.62f*100);
        System.out.println("======test4");
        test4();
    }

    //普通做法，有问题
    private static void test1(){
        System.out.println(10.00-9.60);
    }

    //优化1
    private static void test2(){
        NumberFormat f = new DecimalFormat("#.##");
        System.out.println(f.format(10.00-9.60));
    }

    //优化2：最有方式:保留n为小数时要扩大10的（n+1）次方进行计算
    private static void test3(){
        float f1 = 10.00f;
        float f2 = 9.611f;
        int a =(int) (f1*1000);
        System.out.println("a ="+a);
        int b = (int) (f2*1000);
        System.out.println("b ="+b);
        float r = (a-b);
        System.out.println("a-b="+Math.round(r));
        System.out.println("f:"+r/1000);

    }

    //BigDecimal适合用于金融系统
    public static void test4(){
        BigDecimal a = new BigDecimal(10);
        BigDecimal b = new BigDecimal(9);
        BigDecimal c = a.subtract(b);
       // System.out.println(c);
        System.out.println(c.setScale(2, BigDecimal.ROUND_CEILING));
        System.out.println("c:"+c);
    }
}
